package com.vurtnewk.common.utils

import com.vurtnewk.common.exception.BizCodeEnum
import org.apache.http.HttpStatus
import com.alibaba.fastjson2.TypeReference
import com.alibaba.fastjson2.JSON
import com.baomidou.mybatisplus.core.metadata.IPage
import com.fasterxml.jackson.annotation.JsonInclude

/**
 * @author       vurtnewk
 * @createTime   2025/10/21 23:05
 * @description  结果处理类
 */
@Suppress("unused")
class R : HashMap<String, Any?>() {

    init {
        put(CODE, 0)
        put(MESSAGE, "success")
    }

    companion object {

        const val CODE = "code"
        const val MESSAGE = "message"
        const val DATA = "data"
        const val PAGE = "page"

        fun error(): R {
            return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员")
        }

        fun error(msg: String): R {
            return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg)
        }

        fun error(enum: BizCodeEnum): R {
            return error(enum.code, enum.msg)
        }

        fun error(code: Int, msg: String): R {
            val r = R()
            r[CODE] = code
            r[MESSAGE] = msg
            return r
        }

        fun ok(msg: String): R {
            val r = R()
            r[MESSAGE] = msg
            return r
        }

        fun ok(map: Map<String, Any>): R {
            val r = R()
            r.putAll(map)
            return r
        }

        fun ok(): R {
            return R()
        }

//        fun <T> ok(data: T? = null, page: IPage<T>? = null): R {
//            val r = R()
//            r[""]
//            return R()
//        }

    }

    override fun put(key: String, value: Any?): R {
        super.put(key, value)
        return this
    }

    fun putData(value: Any?): R {
        this[DATA] = value
        return this
    }

    /**
     * 因为泛型擦除的原因，
     * TypeReference实际就是利用匿名内部类 ，通过继承来获取运行时泛型
     */
    fun <T> getData(typeReference: TypeReference<T>): T? {
        val data = this[DATA] ?: return null
        val str = JSON.toJSONString(data)
        return JSON.parseObject(str, typeReference)
    }

    fun <T> getData(key: String, typeReference: TypeReference<T>): T? {
        val data = this[key]
        val str = JSON.toJSONString(data)
        return JSON.parseObject(str, typeReference)
    }

    fun getCode() = this[CODE].toString().toInt()

    fun isSuccess() = this.getCode() == 0
}


